package is.olsenolsen;

import is.Exceptions.*;
import java.util.ArrayList;


public class Langavitleysa  {
	Player activePlayer;
	Player unactivePlayer;
	final char trump;
	Player[] players;
	Deck deck;
	
	// Initialize game
	public Langavitleysa() {
		deck = new Deck(52);
		this.players[0] = (new Player(deck, 26, 0));
		this.players[1] = (new Player(deck, 26, 0));
		
		// randomize trump
		char[] suits = {'h', 's', 'd', 'c'}; 
		double randomNum = Math.random();
		this.trump = suits[(int)randomNum*4];
		
		// randomize starting player
		if((int)randomNum*2 == 1){
			this.activePlayer = players[1];
			this.unactivePlayer = players[0];
		}
		else{
			this.activePlayer = players[0];
			this.unactivePlayer = players[1];
		}
	}
	
	//Notkun: playerCard()
	//Fyrir:  Notendur eru med akvedin spil
	//Eftir:  Spil notenda hafa breysts
	public void playCard() throws GameOverException{
		try{
			ArrayList<Card> cards = activePlayer.drawFromHand(1);
			Card card = cards.remove(0);
			deck.discards.addAll(cards);
			judgeRound(card);
			switchTurn();
		}
		catch(EmptyDeckException e){
			throw new GameOverException(unactivePlayer);
		}
		catch(GameOverException g){
			throw new GameOverException(activePlayer);
		}
	}
	
	
	//Notkun: b = checkTrump(Card spil)
	//Fyrir:  spil er hlutur af gerd Card
	//Eftir:  b er true ef spil er tromp
	//        annars false.
	private boolean checkTrump(Card card) {
		if(this.trump == card.suit){
			return true;
		}
		return false;
	}
	
	private void switchTurn(){
		Player temp;
		temp = this.activePlayer;
		this.activePlayer = this.unactivePlayer;
		this.unactivePlayer = temp;
		
	}
	
	//Notkun: judgeRound(Card card)
	//Fyrir:  card er hlutur af tagi Card
	//Eftir:  Buid er ad uppfaera astand leiks e. umferd
	private void judgeRound(Card card) throws GameOverException{
		boolean isTrump = checkTrump(card);
		
		try{
			if(isTrump){
				if(card.royal){
					deck.discards.addAll(unactivePlayer.drawFromHand(card.value - 9));
				}
				else if(card.value == 1){
					deck.discards.addAll(unactivePlayer.drawFromHand(5));
					}
				else{
					deck.discards.addAll(unactivePlayer.drawFromHand(5));
				}
			}
		}
		catch(EmptyDeckException e){
			throw new GameOverException(activePlayer);
		}
	}

}
